import * as React from 'react';
import { connect } from 'react-redux';
import { get } from 'lodash';

import { Form, Input, Select, Button, message } from 'antd';
import { createTest, updateTest, fetchTestTplList } from 'actions/review';
import { isEqualWithNumber } from 'utils/utils';

interface BasicProps {
  dispatch: (action: any) => any;
  onCreateCallback: (id: any) => any;
  onRemoveCallback: () => any;
  form: any;
  editTest: any;
  tpls: any[];
}

interface BasicState {
  isAddTemplate: boolean;
  templateId: number;
}

class EditBasic extends React.Component<BasicProps, BasicState> {
  static defaultProps: BasicProps = {
    dispatch: () => {},
    onCreateCallback: () => {},
    onRemoveCallback: () => {},
    form: null,
    editTest: null,
    tpls: [],
  };
  constructor(props: BasicProps) {
    super(props);

    this.state = {
      isAddTemplate: false,
      templateId: props.editTest ? props.editTest.templateId : 0,
    };
  }

  componentDidMount() {
    const { editTest } = this.props;
    this.initFormValues(editTest);
  }

  initFormValues(editTest: any) {
    const { form } = this.props;

    const name = get(editTest, 'name', '');
    const description = get(editTest, 'description', '');
    const templateId = get(editTest, 'templateId', '');
    form.setFieldsValue({
      name,
      description,
      templateId,
    });
  }

  componentWillReceiveProps(nextProps: any) {
    const testId = get(nextProps, 'editTest.id', 0);
    const oldTestId = get(this.props, 'editTest.id', 0);
    if (testId !== oldTestId) {
      this.initFormValues(nextProps.editTest);
    }
  }

  handleSubmit = (event: any) => {
    event.preventDefault();

    const { form, dispatch, onCreateCallback, editTest } = this.props;

    form.validateFields((error: any, values: any) => {
      if (error) return;

      const isNewTest = !editTest;
      const action = isNewTest ? createTest(values) : updateTest(editTest.id, values);

      dispatch(action).then((result: any) => {
        if (result.code) {
          message.error(result.msg);
        } else {
          message.success('保存成功');

          const id = isNewTest ? result.response.data : editTest.id;
          onCreateCallback(id);
        }
      });
    });
  };

  getTemplateName(tplId: number) {
    const { tpls } = this.props;
    const tpl = tpls.find((item: any) => {
      return isEqualWithNumber(item.id, tplId);
    });
    if (!tpl) {
      return 'Not Found!!!';
    }

    return tpl.name;
  }

  render() {
    const { form, editTest, tpls, onRemoveCallback } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          <Form.Item label="名称">
            {getFieldDecorator('name', {
              rules: [
                {
                  required: true,
                  message: '试题名称是必填项',
                },
              ],
            })(<Input placeholder="填写试题名称" />)}
          </Form.Item>
          <Form.Item label="模板">
            {getFieldDecorator('templateId', {
              rules: [
                {
                  required: true,
                  message: '试题模板是必选项',
                },
              ],
            })(
              <Select
                showSearch={true}
                disabled={Boolean(editTest)}
                placeholder="选择评测试题模板"
                optionFilterProp="children"
                filterOption={(input: any, option: any) => {
                  return option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}>
                {tpls.map((tpl: any) => {
                  return (
                    <Select.Option value={tpl.id} key={tpl.id}>
                      {tpl.name}
                    </Select.Option>
                  );
                })}
              </Select>
            )}
          </Form.Item>
          <Form.Item>
            <Button size="large" icon="save" type="primary" htmlType="submit">
              &nbsp;&nbsp;&nbsp;提交&nbsp;&nbsp;&nbsp;
            </Button>
            <Button
              style={{ float: 'right' }}
              type="primary"
              className="ant-btn-danger"
              onClick={onRemoveCallback}
              size="large"
              disabled={!editTest}
              icon="delete">
              删除
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

interface OwnProps {
  editTest: any;
  tpls: any[];
}
function mapStateToProps(state: any, ownProps: OwnProps) {
  const { editTest, tpls } = ownProps;

  return {
    editTest,
    tpls,
  };
}

export default connect(mapStateToProps)(Form.create()(EditBasic));
